package com.hrm.common.util;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.storage.persistent.FileRecorder;
import com.qiniu.util.Auth;

import java.io.IOException;
import java.nio.file.Paths;
import java.util.Date;

public class QiniuyunUtils {

    private static final String accessKey = "xUPfYoTVjJhvY1WK3RiqgEX9ELETfvS5BrQDOWmz";
    private static final String secretKey = "DX2W2DtIv05Mp14fqLXBcct1y5VTLeD";
    private static final String bucket = "lcm-hrm";
    private static final String prix = "http://qvq4a1cvv.hb-bkt.clouddn.com/";
    private static final String localTempDir = Paths.get(System.getenv("java.io.tmpdir"), bucket).toString();
    private UploadManager uploadManage;

    public QiniuyunUtils() throws IOException {
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.huabei());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
        cfg.resumableUploadMaxConcurrentTaskCount = 2;  // 设置分片上传并发，1：采用同步上传；大于1：采用并发上传
        //...其他参数参考类注释
        //设置断点续传文件进度保存目录
        FileRecorder fileRecorder = new FileRecorder(localTempDir);
        uploadManage = new UploadManager(cfg, fileRecorder);
    }

    //断点续传
    public String uploadQiniuyun(String imgName, byte[] bytes) {
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket,imgName);
        try {
            Response response = uploadManage.put(bytes, imgName, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            return prix + putRet.key + "?t=" + new Date().getTime(); //回写数据
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        }
        return null;
    }




}
